<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      @returnBack="$emit('returnModify')"
    >
      <template v-slot:full-button>
        <el-button :disabled="!canSave" v-if="!orderId && $permission('withTableOrder:saveAndSubmit')" @click="saveAndSubmit()">保存并提交</el-button>
        <el-button :disabled="!canSave" @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-deptName>
              <el-input
                v-model="formInfo.data.deptName"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择部门"
              >
                <template #append>
                  <el-icon @click="_selectDept"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct"
                >添加手术包
              </el-button>
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除手术包
              </el-button>
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :tab-index="false"
                :checkbox="true"
                :isRowClickSelect="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.qty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positive,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              v-model.lazy="scope.row.qty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="999999999"
                              @change="
                                changeLarge($event, `data.${scope.$index}.qty`)
                              "
                            />
                          </el-form-item>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!-- 选择部门 -->
    <select-dept
      v-if="deptInfo.visible"
      v-model:show-dialog="deptInfo.visible"
      :query="deptInfo.query"
      :check-box="false"
      :highlight-row="true"
      :save-empty="true"
      @callback="selectDeptCallback"
    />
    <SelectWithTableKit
      v-if="withTableKitInfo.visible"
      v-model:show-dialog="withTableKitInfo.visible"
      :query="withTableKitInfo.query"
      :check-box="true"
      table-key="withTableOrderModifyQueryKit-com.slip.spd.entity.vo.withtable.WithTableOrderKitVO
"
      @callback="withTableKitBack"
    />
  </div>
</template>

<script setup name="withTableOrderModify">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'

import SelectDept from '@/components/SelectDept/index'
import SelectWithTableKit from '@/components/SelectWithTableKit/index'
import {
  getWithTableOrderById,
  getWithTableOrderKitAll,
  createWithTableOrder,
  createWithTableOrderAndSave,
  updateWithTableOrder,
} from '@/api/withTable.js'
import { getCustomizeSetting } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const props = defineProps(['visible', 'title', 'orderId'])

//表单相关
const formInfo = reactive({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    remark: '',
  },
  fieldList: [
    {
      label: '部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    deptName: [{ required: true, message: '请选择部门', trigger: 'change' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.orderId,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'scanCode' },
  ],
})
// 表格相关
const tableInfo = reactive({
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '删除手术包',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
const deptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const withTableKitInfo = reactive({
  visible: false,
  query: {
    id: {
      queryType: 'NOT_IN',
      queryCategory: 'AND',
      value: '',
    },
    deptId: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: '',
    },
  },
})

const formRefs = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.data.length
})
const canAddProduct = computed(() => {
  return formInfo.data.deptId
})
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length
})

let obj = {
  name: {
    label: '名称',
    value: 'name',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'slot',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableOrder:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableOrder:price'),
    hidden: true,
  },
  productionDate: {
    label: '生成日期',
    value: 'productionDate',
    type: 'slot',
    minWidth: '160px',
    hidden: true,
  },
  validityDate: {
    label: '失效日期',
    value: 'validityDate',
    minWidth: '160px',
    type: 'slot',
    hidden: true,
  },
  batchNumber: {
    label: '批号',
    value: 'batchNumber',
    type: 'slot',
    hidden: true,
  },
  defaultSupplierName: {
    label: '默认供应商',
    value: 'defaultSupplierName',
    type: 'column',
    hidden: true,
  },
  defaultSupplierCode: {
    label: '默认供应商编码',
    value: 'defaultSupplierCode',
    type: 'column',
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableOrder:price'),
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
if (!props.orderId) {
  formInfo.fieldList = formInfo.fieldList.filter(
    (item) => item.value !== 'orderNo'
  )
}

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  })
})

function changeLarge(e, str) {
  proxy.$nextTick(() => {
    proxy.$refs.tableForm.clearValidate(str)
  })
}
function addProduct() {
  //选择手术包
  withTableKitInfo.visible = true
  let ids = tableInfo.data.map((item) => item.kitId)
  withTableKitInfo.query.id.value = ids && ids.length ? ids.toString() : ''
  withTableKitInfo.query.deptId.value = formInfo.data.deptId
}
function withTableKitBack(data) {
  //手术包返回
  if (data && data.length) {
    data.forEach((item) => {
      item['kitId'] = item.id
      item.kitStatusValue = item.statusValue
      item.kitStatus = item.status
      item.kitSupplierName = item.supplierName
      item.kitSupplierId = item.supplierId
      item.kitDeptName = item.deptName
      item.kitDeptId = item.deptId
    })
    tableInfo.data = data.concat(tableInfo.data)
  }
}
function getList() {
  getWithTableOrderKitAll(filterInfo.query).then((res) => {
    if (res && res.success) {
      tableInfo.data = res.data
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = props.orderId ? updateWithTableOrder : isSaveAndSubmit === true ? createWithTableOrderAndSave : createWithTableOrder
    tableInfo.data.forEach((item) => {
      item.calcQty = item.qty
    })
    let data = formInfo.data
    data.mergeDetails = proxy.$fn.filterBlacklist(tableInfo.data)
    api(data).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        emit('returnModify')
      }
    })
  })
}

function _selectDept() {
  deptInfo.visible = true
}
function selectDeptCallback(row) {
  if (row && row.id) {
    formInfo.data.deptName = row.name
    formInfo.data.deptId = row.id
    tableInfo.data = []
  } else {
    formInfo.data.deptName = ''
    formInfo.data.deptId = ''
    tableInfo.data = []
  }
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.kitId) {
    tableInfo.data = tableInfo.data.filter((row) => row !== selectRow)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.data = tableInfo.data.filter(
          (row) => !tableInfo.selections.includes(row)
        )
      })
  }
}

function getCustomize() {
  let param = {
    tableKey:
      'withTableOrderModify-com.slip.spd.entity.vo.withtable.WithTableOrderKitVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      filterInfo.query.customizeUserVO = data
      if (props.orderId) {
        getMain()
      }
    }
  })
}
function getMain() {
  getWithTableOrderById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.data = res.data
      getList()
    }
  })
}
</script>
